package no547;

class Solution {
    public int findCircleNum(int[][] isConnected) {
        UniFind uniFind = new UniFind(isConnected.length);

        for (int i = 1; i < isConnected.length; i++) {
            for (int j = i+1; j < isConnected.length; j++) {
                if (isConnected[i][j] == 1){
                    uniFind.union(i,j);
                }
            }
        }

        return uniFind.getCount();
    }
}

class UniFind {
    private int[] parents;
    private int count;

    public UniFind(int i) {
        this.parents = new int[i];
        this.count = i;
        for (int j = 0; j < i; j++) {
            parents[j]=j;
        }
    }

    public int getCount() {
        return count;
    }

    public int find(int x){
        if( x != parents[x]){
            parents[x] = find(parents[x]);
        }
        return parents[x];
    }

    public void union(int a, int b){
        if (find(a)!=find(b)){
            parents[find(a)] =find(b);
            count--;
        }

    }
}